package com.suisung.shopsuite.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;

public class JsonToXmlUtils {

    public static String json2xml(JSONObject jsonObj) {
        StringBuffer buff = new StringBuffer();
        JSONObject tempObj = null;
        JSONArray tempArr = null;
        for (String temp : jsonObj.keySet()) {
            buff.append("<" + temp.trim() + ">");
            //buff.append("<![CDATA[" + temp.trim() + ">");

            jsonObj.get(temp);
            if (jsonObj.get(temp) instanceof JSONObject) {
                tempObj = (JSONObject) jsonObj.get(temp);
                buff.append(json2xml(tempObj));
            } else if (jsonObj.get(temp) instanceof JSONArray) {
                tempArr = (JSONArray) jsonObj.get(temp);
                if (tempArr.size() > 0) {
                    for (int i = 0; i < tempArr.size(); i++) {
                        tempObj = (JSONObject) tempArr.get(0);
                        buff.append(json2xml(tempObj));
                    }
                }
            } else {
                String tempStr = jsonObj.get(temp).toString();
                buff.append(tempStr.trim());
            }
            buff.append("</" + temp.trim() + ">");
            //buff.append("</" + temp.trim() + "]]>");
        }
        return buff.toString();
    }

    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"\\u5F20\\u4E09\",\"addtime\":\"2014-01-01\",\"username\":\"abc\",\"id\":5,\"rows\":[{\"a\":100,\"b\":200}]}";
        JSONObject jsonObj = JSONObject.parseObject(jsonStr, Feature.OrderedField);
        String xmlStr = JsonToXmlUtils.json2xml(jsonObj);
        xmlStr = "<xml>" + xmlStr + "</xml>";
        System.out.println(xmlStr);
    }
}